package com.fmob.client.app.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Process;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.fmob.client.app.activity.AppAutoInitializer;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.ResultBean;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.manager.FMSdk;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.RetrofitFactory;

public class FMApplication extends Application {

    //进行耗时操作的非UI线程池
    private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(10);
    public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(5, 128, 1, TimeUnit.SECONDS, sPoolWorkQueue);

    public Executor getExecutor() {
        return THREAD_POOL_EXECUTOR;
    }

    public static int messageSoundCount = 0;
    private static FMApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        FMSdk.init(this);
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean firstOpenAgress = sharedPrefs.getBoolean(Constant.FIRST_OPEN_AGREE, false);
        if (firstOpenAgress) {
            AppAutoInitializer.getInstance().initNeedPermissionsSDK(this);
        }
        Utils.init(this);
        //只允许有一个application,避免多次开启服务
        final String curProcess = getProcessName(this, Process.myPid());
        if (!getPackageName().equals(curProcess)) {
            return;
        }

    }

    public static FMApplication getInstance() {
        return instance;
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null && !runningApps.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        }
        return null;
    }

    public void getCrcSize() {
        try {
            ZipFile zipfile = new ZipFile(getPackageCodePath());
            final ZipEntry dexentry = zipfile.getEntry("classes.dex");
            XLog.i("dexentry:" + dexentry.getCrc());
            String time = (String) Utility.getMetaData(this, Constant.FMC_VERSION_TIME);
            if (!TextUtils.isEmpty(time)) {
                String[] split = time.split("_");
                ApiFactory.getFactory().create(UserApi.class).getCrcSize("http://202.105.104.99:9000/uc/mobile/getCrcSize", split[1])
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<ResultBean>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onNext(ResultBean result) {//成功后向后台发送GPS数据
                                if (!result.getRecord().equals(String.valueOf(dexentry.getCrc()))) {
                                    System.exit(0);
                                }
                            }
                        });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
